//
//  TTHttpRequest.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/6/3.
//  Copyright © 2019 王洋. All rights reserved.
//
#import "NSDate+InternetDateTime.h"
#import "TTUserModel.h"
#import "AFNetworking.h"
#import "TTHttpRequest.h"
#import "TTUDIDManager.h"
#import "LoginViewController.h"
#import "V_LoginViewController.h"
#import "LoginViewController.h"

@implementation TTHttpRequest

- (void)getStart {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10.0;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
    
    [manager.requestSerializer setValue:[TTUserModel sharedObject].installModel.scaId
                     forHTTPHeaderField:@"channel"];//channel
    [manager.requestSerializer setValue:[Utilities getDeviceIdentifier]
                     forHTTPHeaderField:@"deviceModel"];//device
    NSString *systemVersion = [NSString stringWithFormat:@"IOS%.2f",[[[UIDevice currentDevice] systemVersion] floatValue]];
    [manager.requestSerializer setValue:systemVersion
                     forHTTPHeaderField:@"systemVersion"];//sys version
    [manager.requestSerializer setValue:[TTUDIDManager getUniqueDeviceID]
                     forHTTPHeaderField:@"deviceUniqueNo"];//idfa
    [manager.requestSerializer setValue:APP_VERSION
                     forHTTPHeaderField:@"appVersionCode"];//app version
    [manager.requestSerializer setValue:@"2"
                     forHTTPHeaderField:@"platformId"];//1-安卓，2-ios
    
    if ([TTUserModel sharedObject].installModel.scaId.length == 0) {
        [manager.requestSerializer setValue:@"apple"
                         forHTTPHeaderField:@"appStore"];//1-安卓，2-ios
    }

    
    [manager.requestSerializer setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];

    NSLog(@"url:%@ \n parameters:%@", self.url, self.getData);
    [manager GET:self.url parameters:self.getData headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *jsonDict = [Utilities dictionaryWithJsonString:responseObject];
            self.finishBlock(jsonDict);
            
            if ([jsonDict isKindOfClass:[NSDictionary class]]) {
                NSInteger code = [[jsonDict valueForKey:@"code"] integerValue];
                if (code == 401) {
                    [self goLoginWithMessage:[jsonDict valueForKey:@"message"]];
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            self.failedBlock(error);
        }];
}

- (void)postStart {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10.0;
    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];

    [manager.requestSerializer setValue:[TTUserModel sharedObject].installModel.scaId
                     forHTTPHeaderField:@"channel"];//channel
    [manager.requestSerializer setValue:[Utilities getDeviceIdentifier]
                     forHTTPHeaderField:@"deviceModel"];//device
    NSString *systemVersion = [NSString stringWithFormat:@"IOS%.2f",[[[UIDevice currentDevice] systemVersion] floatValue]];
    [manager.requestSerializer setValue:systemVersion
                     forHTTPHeaderField:@"systemVersion"];//sys version
    [manager.requestSerializer setValue:[TTUDIDManager getUniqueDeviceID]
                     forHTTPHeaderField:@"deviceUniqueNo"];//idfa
    [manager.requestSerializer setValue:APP_VERSION
                     forHTTPHeaderField:@"appVersionCode"];//app version
    [manager.requestSerializer setValue:@"2"
                     forHTTPHeaderField:@"platformId"];//1-安卓，2-ios
    if ([TTUserModel sharedObject].installModel.scaId.length == 0) {
        [manager.requestSerializer setValue:@"apple"
                         forHTTPHeaderField:@"appStore"];//1-安卓，2-ios
    }
    
    [manager.requestSerializer setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];
    NSLog(@"url:%@ \n parameters:%@", self.url, self.postData);
    [manager POST:self.url parameters:self.postData headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *jsonDict = [Utilities dictionaryWithJsonString:responseObject];
            self.finishBlock(jsonDict);
            [self refreshTimeWithTask:task AndID:responseObject];

            if ([jsonDict isKindOfClass:[NSDictionary class]]) {
                
                NSInteger code = [[jsonDict valueForKey:@"code"] integerValue];
                if (code == 10005) {
                    [self goLoginWithMessage:[jsonDict valueForKey:@"message"]];
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            self.failedBlock(error);
    }];
}
+ (void)postWithUrl:(NSString *)url parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    request.timeoutInterval = 10;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10.0;
    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];

    [manager.requestSerializer setValue:[TTUserModel sharedObject].installModel.scaId
                     forHTTPHeaderField:@"channel"];//channel
    [manager.requestSerializer setValue:[Utilities getDeviceIdentifier]
                     forHTTPHeaderField:@"deviceModel"];//device
    NSString *systemVersion = [NSString stringWithFormat:@"IOS%.2f",[[[UIDevice currentDevice] systemVersion] floatValue]];
    [manager.requestSerializer setValue:systemVersion
                     forHTTPHeaderField:@"systemVersion"];//sys version
    [manager.requestSerializer setValue:[TTUDIDManager getUniqueDeviceID]
                     forHTTPHeaderField:@"deviceUniqueNo"];//idfa
    [manager.requestSerializer setValue:APP_VERSION
                     forHTTPHeaderField:@"appVersionCode"];//app version
    [manager.requestSerializer setValue:@"2"
                     forHTTPHeaderField:@"platformId"];//1-安卓，2-ios
    if ([TTUserModel sharedObject].installModel.scaId.length == 0) {
        [manager.requestSerializer setValue:@"apple"
                         forHTTPHeaderField:@"appStore"];//1-安卓，2-ios
    }
    [manager.requestSerializer setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];
    
    [request setValue:[TTUserModel sharedObject].installModel.scaId forHTTPHeaderField:@"channel"];
    [request setValue:[Utilities getDeviceIdentifier] forHTTPHeaderField:@"deviceModel"];
    [request setValue:systemVersion forHTTPHeaderField:@"systemVersion"];
    [request setValue:[TTUDIDManager getUniqueDeviceID] forHTTPHeaderField:@"deviceUniqueNo"];
    [request setValue:APP_VERSION forHTTPHeaderField:@"appVersionCode"];
    [request setValue:@"2" forHTTPHeaderField:@"platformId"];
    if ([TTUserModel sharedObject].installModel.scaId.length == 0) {
        //1-安卓，2-ios
        [request setValue:@"apple" forHTTPHeaderField:@"appStore"];
    }
    [request setValue:[TTUserModel sharedObject].token forHTTPHeaderField:@"token"];
    NSLog(@"url:%@ \n parameters:%@", url, parameters);
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error != nil) {
            failure(nil, error);
        } else {
            success(nil, responseObject);
        }
    }]resume];
}

- (void)goLoginWithMessage:(NSString *)msg {
    
    [[TTUserModel sharedObject] initialization]; //userModel清空当前用户的所有信息
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        UIViewController *viewController = [Utilities topViewController];
        if (![viewController isKindOfClass:[V_LoginViewController class]]) {
            V_LoginViewController* login = [[V_LoginViewController alloc] init];
        //if (![viewController isKindOfClass:[LoginViewController class]]) {
            //LoginViewController* login = [[LoginViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
            nav.navigationBar.translucent = NO;
            UIViewController *spVc = viewController.navigationController? viewController.navigationController: viewController;
            nav.modalPresentationStyle = UIModalPresentationFullScreen;
            [spVc presentViewController:nav animated:YES completion:nil];
        }
    });
}

- (void)refreshTimeWithTask:(NSURLSessionDataTask * _Nonnull) task AndID:(id _Nullable)responseObject {
    
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
    NSDictionary *allHeaders = response.allHeaderFields;
    NSString *dateServer = [allHeaders valueForKey:@"Date"];
    NSDate *inputDate = [NSDate dateFromRFC822String:dateServer];
    NSTimeInterval serverTimeStamp = [Utilities getTimestampWithDate:inputDate];
    [[NSUserDefaults standardUserDefaults] setDouble:serverTimeStamp forKey:@"kLastSaveServerTimeStamp"];
    NSTimeInterval currentLocalTimeStamp = [Utilities getCurrentTimestamp];
    
    [[NSUserDefaults standardUserDefaults] setDouble:currentLocalTimeStamp forKey:@"kLastSaveLocalTimeStamp"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
